<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';
const newsOptions = ref([])
import { useVbenForm } from '#/adapter/form';
import { getPageInfo_news, postPage_news, putPage_news,getPage_carByname } from '#/api/portal/vechiledetail';
import { usePreferencesStore } from '#/store';
import { getPage_news as car_model } from '#/api/portal/carmodel';
const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_title: '',
    post_alias: '',
    more: {
      thumbnail: '',
    },
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
        component: 'Select',
        fieldName: 'car_model',
        label: `选择车型`,
        componentProps: {
            class: 'w-full',
            placeholder: '选择车型',
            options:newsOptions,

        },
        rules:'required'
     },

    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: `${routeTitle}属性`,
       rules: z.string().max(30,'字符不能超过100'),
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.news_title;
          state.form.name = values.name;
          state.form.title = values.title;
          state.form.des = values.des;
          state.form.images = values.images;
          state.form.car_model = values.car_model;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'name',
          'des',
          'images',
          'car_model'
        ],
      },
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'title',
      label: `${routeTitle}标题`,
      rules: z.string().max(150,'标题不能超过150'),
    },
 

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
        style: {
          height: '150px',
        },
      },
      fieldName: 'des',
      label: `${routeTitle}描述`,
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'images',
      label: `${routeTitle}缩略图`,
    },

  ],
});

async function onSubmit() {
  const values: any = state.form;

  let response;

  if (values.id) {
    response = await putPage_news(values);
  } else {
    delete values.id;
    response = await postPage_news(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || '操作成功');
    closeCurrentTab();
    router.push({ name: 'Portalvechiledetail' });
  } else {
    message.error(msg || '操作失败'); 
  }
}


async function onGetPage(id: number) {
  const { data } = await getPageInfo_news({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    name: data?.name ?? '',
    des: data?.des ?? '',
    images: data?.images ?? [],
    car_model:data?.car_model??''
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  if(index.value>0){
      await onGetPage(index.value);
  }
  onSearchNews();
});


const onSearchNews = async () => {

 const res = await car_model();

  newsOptions.value = (res?.data?.list || []).map(item => ({
    label: item.category_name+' '+ item.name,
    value: item.id,
  }))

}
</script>

<template>
  <Page>
    <Card :title="`${routeTitle}详情`">
      <BasicForm />
    </Card>
  </Page>
</template>
